import sys

from PySide6.QtGui import QFont
from PySide6.QtWidgets import (QApplication, QMainWindow, QTextEdit, QVBoxLayout,
                               QWidget, QPushButton, QHBoxLayout, QLabel,
                               QGroupBox, QFormLayout, QComboBox, QSplitter,
                               QCheckBox, QLineEdit, QMessageBox, QRadioButton)
from PySide6.QtCore import Qt
from qt_material import apply_stylesheet


class TextJoinerUI(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('文本连接/拆分工具')

        # 创建中央部件和布局
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 创建分割器实现两栏布局
        splitter = QSplitter(Qt.Horizontal)
        splitter.setHandleWidth(5)
        splitter.setSizes([400, 800])  # 设置初始大小比例
        
        # 左侧控制面板
        left_panel = QWidget()
        left_layout = QVBoxLayout(left_panel)
        
        # 创建模式选择区域
        mode_group = QGroupBox("操作模式")
        mode_layout = QHBoxLayout()
        self.join_mode_radio = QRadioButton("连接模式")
        self.split_mode_radio = QRadioButton("拆分模式")
        self.join_mode_radio.setChecked(True)  # 默认连接模式
        mode_layout.addWidget(self.join_mode_radio)
        mode_layout.addWidget(self.split_mode_radio)
        mode_group.setLayout(mode_layout)

        # 创建连接符设置区域
        separator_group = QGroupBox("分隔符设置")
        separator_layout = QFormLayout()

        # 预设连接符选择
        self.separator_combo = QComboBox()
        self.separator_combo.addItem("顿号 (、)", "、")
        self.separator_combo.addItem("逗号 (,)", ",")
        self.separator_combo.addItem("分号 (;)", ";")
        self.separator_combo.addItem("短横线 (-)", "-")
        self.separator_combo.addItem("下划线 (_)", "_")
        self.separator_combo.addItem("竖线 (|)", "|")
        self.separator_combo.addItem("空格 ( )", " ")
        self.separator_combo.addItem("自定义", "custom")
        self.separator_combo.setCurrentIndex(0)  # 设置默认选中顿号
        self.separator_combo.currentIndexChanged.connect(self.on_separator_changed)

        # 自定义连接符输入框
        self.custom_separator_edit = QLineEdit()
        self.custom_separator_edit.setPlaceholderText("输入自定义分隔符")
        self.custom_separator_edit.setEnabled(False)  # 默认禁用

        separator_layout.addRow(QLabel("预设分隔符:"), self.separator_combo)
        separator_layout.addRow(QLabel("自定义分隔符:"), self.custom_separator_edit)
        separator_group.setLayout(separator_layout)

        # 去重选项
        deduplicate_group = QGroupBox("去重选项")
        deduplicate_layout = QVBoxLayout()
        self.deduplicate_checkbox = QCheckBox("去除重复项")
        self.deduplicate_checkbox.setChecked(True)  # 默认勾选去重选项
        # 为复选框设置专门的样式以解决qt_material主题下的显示问题
        self.deduplicate_checkbox.setStyleSheet("""
            QCheckBox::indicator {
                width: 18px;
                height: 18px;
                border: 2px solid #555;
                border-radius: 3px;
                background-color: transparent;
            }
            QCheckBox::indicator:checked {
                background-color: #4CAF50;
                border: 2px solid #4CAF50;
            }
            QCheckBox::indicator:unchecked {
                background-color: transparent;
                border: 2px solid #555;
            }
        """)
        # 连接去重选项状态变化到处理函数
        self.deduplicate_checkbox.stateChanged.connect(self.process_text_automatically)
        deduplicate_layout.addWidget(self.deduplicate_checkbox)
        deduplicate_group.setLayout(deduplicate_layout)

        # 连接模式切换信号
        self.join_mode_radio.toggled.connect(self.on_mode_changed)
        self.split_mode_radio.toggled.connect(self.on_mode_changed)

        # 添加控件到左侧布局
        left_layout.addWidget(mode_group)
        left_layout.addWidget(separator_group)
        left_layout.addWidget(deduplicate_group)
        left_layout.addStretch()

        # 右侧文本编辑区域
        right_panel = QWidget()
        right_layout = QVBoxLayout(right_panel)
        
        # 创建输入区域
        input_group = QGroupBox("输入文本")
        input_layout = QVBoxLayout()
        self.input_edit = QTextEdit()
        self.input_edit.setFont(QFont('宋体', 12))
        self.input_edit.setPlaceholderText("在此输入文本，每行一条记录...")
        # 连接文本更改信号到处理函数
        self.input_edit.textChanged.connect(self.process_text_automatically)
        input_layout.addWidget(self.input_edit)
        input_group.setLayout(input_layout)
        
        # 创建输出区域
        output_group = QGroupBox("输出结果")
        output_layout = QVBoxLayout()
        self.output_edit = QTextEdit()
        self.output_edit.setFont(QFont('宋体', 12))
        self.output_edit.setPlaceholderText("处理后的结果将显示在这里...")
        self.output_edit.setReadOnly(True)  # 输出框设为只读
        output_layout.addWidget(self.output_edit)
        output_group.setLayout(output_layout)
        
        right_layout.addWidget(input_group)
        right_layout.addWidget(output_group)
        
        # 创建按钮区域
        button_layout = QHBoxLayout()

        # 处理按钮
        process_btn = QPushButton('处理文本')
        process_btn.clicked.connect(self.join_text)
        join_btn = process_btn

        # 清空按钮
        clear_btn = QPushButton('清空')
        clear_btn.clicked.connect(self.clear_text)

        # 复制按钮
        copy_btn = QPushButton('复制结果')
        copy_btn.clicked.connect(self.copy_result)

        button_layout.addWidget(join_btn)
        button_layout.addWidget(clear_btn)
        button_layout.addStretch()
        button_layout.addWidget(copy_btn)
        
        right_layout.addLayout(button_layout)

        # 将左右面板添加到分割器
        splitter.addWidget(left_panel)
        splitter.addWidget(right_panel)
        
        # 创建主布局并添加分割器
        main_layout = QVBoxLayout(central_widget)
        main_layout.addWidget(splitter)
        
        # 添加版权信息
        copyright_label = QLabel("版权所有© Copyright玉师人事处")
        copyright_label.setAlignment(Qt.AlignCenter)
        main_layout.addWidget(copyright_label)
        
        # 创建状态栏
        self.statusBar().showMessage('就绪')

    def on_separator_changed(self, index):
        """当连接符选择改变时"""
        if index >= 0 and self.separator_combo.itemData(index) == "custom":
            self.custom_separator_edit.setEnabled(True)
        else:
            self.custom_separator_edit.setEnabled(False)
        # 当连接符改变时也自动处理文本
        self.process_text_automatically()

    def join_text(self):
        """连接文本（手动触发）"""
        self.process_text_automatically()

    def on_mode_changed(self, checked):
        """当模式改变时"""
        if checked:  # 只有在选中时才处理
            self.process_text_automatically()
            # 更新输入框的提示文本
            if self.join_mode_radio.isChecked():
                self.input_edit.setPlaceholderText("在此输入文本，每行一条记录...")
                self.output_edit.setPlaceholderText("连接后的结果将显示在这里...")
            else:
                self.input_edit.setPlaceholderText("在此输入用分隔符连接的文本...")
                self.output_edit.setPlaceholderText("拆分后的结果将显示在这里...")

    def process_text_automatically(self):
        """自动处理文本"""
        # 获取输入文本
        input_text = self.input_edit.toPlainText()
        if not input_text.strip():
            self.output_edit.setPlainText("")
            self.statusBar().showMessage('就绪')
            return

        # 获取连接符
        current_index = self.separator_combo.currentIndex()
        separator = self.separator_combo.itemData(current_index)
        if separator == "custom":
            separator = self.custom_separator_edit.text()
        # 如果还是空的，则使用默认顿号
        if separator is None or separator == "":
            separator = "、"

        if self.join_mode_radio.isChecked():
            # 连接模式
            # 解析文本行并自动去除每行前后空格
            lines = input_text.strip().split('\n')
            items = [line.strip() for line in lines if line.strip()]

            # 去重处理
            if self.deduplicate_checkbox.isChecked():
                # 保持原有顺序的去重
                seen = set()
                items = [x for x in items if not (x in seen or seen.add(x))]

            # 连接文本
            result = separator.join(items)
            self.statusBar().showMessage(f'连接完成，共 {len(items)} 项')
        else:
            # 拆分模式
            items = input_text.strip().split(separator)
            # 去除空白项
            items = [item.strip() for item in items if item.strip()]
            
            # 去重处理
            if self.deduplicate_checkbox.isChecked():
                # 保持原有顺序的去重
                seen = set()
                items = [x for x in items if not (x in seen or seen.add(x))]
            
            # 拆分文本
            result = "\n".join(items)
            self.statusBar().showMessage(f'拆分完成，共 {len(items)} 项')

        # 显示结果
        self.output_edit.setPlainText(result)

    def clear_text(self):
        """清空文本"""
        self.input_edit.clear()
        self.output_edit.clear()
        self.statusBar().showMessage('已清空文本')

    def copy_result(self):
        """复制结果到剪贴板"""
        result = self.output_edit.toPlainText()
        if result:
            clipboard = QApplication.clipboard()
            clipboard.setText(result)
            self.statusBar().showMessage('结果已复制到剪贴板')
        else:
            QMessageBox.warning(self, '警告', '没有结果可复制！')


def main():
    app = QApplication(sys.argv)
    window = TextJoinerUI()
    apply_stylesheet(app, theme='dark_lightgreen.xml', invert_secondary=False)
    # 为复选框使用Fusion样式以确保勾选标记可见
    window.deduplicate_checkbox.setStyle(QApplication.style())
    window.show()
    sys.exit(app.exec())


if __name__ == '__main__':
    main()